package com.maltys.sign_aspect.util;

import com.maltys.sign_aspect.ErrorCode;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author luonankun
 * @date 2022/10/21
 **/
public class SignStrategyAdapter implements SignStrategy {
    /**
     * 请求接口验签
     *
     * @param request
     * @param signKey
     * @param appKeyIdx
     * @return
     */
    @Override
    public Boolean checkSign(HttpServletRequest request, String signKey, int[][] appKeyIdx) throws Exception {
        String requestSign = getRequestSign(request);
        if (StringUtils.isEmpty(requestSign)) {
            throw new Exception(ErrorCode.APP_SIGNATURE_ERROR.getMsg());
        }
        Map<String, Object> paramsMap = getRequestParams(request);
//        String signSrc = ParametersInclude.concatParamsSingleValue(paramsMap);
//        return ParametersInclude.checkSignSdk(signKey, appKeyIdx, signSrc, requestSign);
        return null;
    }

    protected String getRequestSign(HttpServletRequest request) {
        String requestSign = request.getParameter(SIGN);
        if (StringUtils.isEmpty(requestSign)) {
            requestSign = request.getHeader(SIGN);
        }
        return requestSign;
    }

    protected Map<String, Object> getRequestParams(HttpServletRequest request) throws Exception {
        Enumeration<String> parameterNames = request.getParameterNames();
        Map<String, Object> paramMap = new HashMap<>();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            if (!SIGN.equals(name)) {
                paramMap.put(name, request.getParameter(name));
            }
        }
        return paramMap;
    }
}
